package com.kaia.shoebox.activity;

import java.util.Date;
import java.util.List;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.Intent;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.kaia.shoebox.Intents;
import com.kaia.shoebox.R;
import com.kaia.shoebox.adapter.OnDatabaseActionListener;
import com.kaia.shoebox.adapter.SwitchFragmentListener;
import com.kaia.shoebox.db.DbHelper;
import com.kaia.shoebox.db.dao.Importance;
import com.kaia.shoebox.db.dao.TodoItem;
import com.kaia.shoebox.fragment.BaseListFragment;
import com.kaia.shoebox.fragment.DoneListFragment;
import com.kaia.shoebox.fragment.TodoListFragment;
import com.kaia.shoebox.loader.TodoListLoader;

public class ShoeboxMain extends OrmLiteBaseActivity<DbHelper> implements
		OnDatabaseActionListener {

	private static final String TAG = ShoeboxMain.class.getSimpleName();

	public static final String CURRENT_LIST_FRAGMENT_TAG = "CurrentList";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		
		if (savedInstanceState == null) {
			BaseListFragment fragment = mFrag;
			FragmentTransaction trans = mActivity.getFragmentManager()
					.beginTransaction();
			trans.replace(R.id.fragment_list_container, fragment,
					ShoeboxMain.CURRENT_LIST_FRAGMENT_TAG);
			trans.commit();
		}

		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayShowTitleEnabled(false);

		Tab tab = actionBar
				.newTab()
				.setText("Not Done")
				.setTabListener(
						new SwitchFragmentListener<TodoListFragment>(this,
								new TodoListFragment(), savedInstanceState));

		tab = actionBar
				.newTab()
				.setText("Done")
				.setTabListener(
						new SwitchFragmentListener<DoneListFragment>(this,
								new DoneListFragment(), savedInstanceState));

		actionBar.addTab(tab);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case Intents.NEW_TODO_INTENT:
			if (resultCode == RESULT_OK) {
				String title = data.getStringExtra("title");
				long due = data.getLongExtra("due", 0);
				String notes = data.getStringExtra("notes");
				int imp = data.getIntExtra("importance", 0);

				Date dueDate = new Date(due);
				Importance importance = Importance.getImprtanceByNumber(imp);

				addTodo(new TodoItem(title, dueDate, notes, importance));
			}
			break;
		case Intents.EDIT_TODO_INTENT:
			if (resultCode == RESULT_OK) {
				int id = data.getIntExtra("_id", 0);
				String title = data.getStringExtra("title");
				long due = data.getLongExtra("due", 0);
				String notes = data.getStringExtra("notes");
				int imp = data.getIntExtra("importance", 0);

				Date dueDate = new Date(due);
				Importance importance = Importance.getImprtanceByNumber(imp);

				editTodo(new TodoItem(id, title, dueDate, importance, notes));
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_action_bar, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		BaseListFragment frag = (BaseListFragment) getFragmentManager()
				.findFragmentByTag(CURRENT_LIST_FRAGMENT_TAG);

		switch (item.getItemId()) {
		case R.id.action_new:
			Intent intent = new Intent(ShoeboxMain.this, NewTodoActivity.class);
			startActivityForResult(intent, Intents.NEW_TODO_INTENT);
			break;
		case R.id.action_sort_by_due_date:
			if (frag.isAdded()) {
				frag.sortByDueDate();
			}
			Log.i(TAG, "Sorting list by due date");
			break;
		case R.id.action_sort_by_importance:
			Log.i(TAG, "Sorting list by importance");
			if (frag.isAdded()) {
				frag.sortByImportance();
			}
			break;
		case R.id.action_sort_by_creation_date:
			Log.i(TAG, "Sorting list by created date");
			if (frag.isAdded()) {
				frag.sortByCreationDate();
			}
			break;
		}

		return true;
	}

	@Override
	public boolean deleteTodo(TodoItem item) {
		final RuntimeExceptionDao<TodoItem, Integer> todoDao = getHelper()
				.getRuntimeDao();

		if (todoDao.delete(item) == 1) {
			Toast.makeText(this, "Successfully deleted item",
					Toast.LENGTH_SHORT).show();
			return true;
		} else {
			Log.e(TAG, "Couldn't delete item from database");
			Toast.makeText(this, "Couldn't delete item", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
	}

	@Override
	public boolean addTodo(TodoItem item) {
		RuntimeExceptionDao<TodoItem, Integer> todoDao = getHelper()
				.getRuntimeDao();

		if (todoDao.create(item) != 1) {
			Log.e(TAG, "couldn't add element to database");
			Toast.makeText(this, "Error adding item", Toast.LENGTH_LONG).show();
			return false;
		}

		TodoListFragment frag = (TodoListFragment) getFragmentManager()
				.findFragmentByTag(CURRENT_LIST_FRAGMENT_TAG);

		frag.addNewTodo(item);

		return true;
	}

	@Override
	public boolean editTodo(TodoItem item) {
		RuntimeExceptionDao<TodoItem, Integer> todoDao = getHelper()
				.getRuntimeDao();

		if (todoDao.update(item) != 1) {
			Log.e(TAG, "couldn't update element in the database");
			Toast.makeText(this, "Error updating item", Toast.LENGTH_LONG)
					.show();
			return false;
		}

		TodoListFragment frag = (TodoListFragment) getFragmentManager()
				.findFragmentByTag(CURRENT_LIST_FRAGMENT_TAG);

		frag.updateTodo(item);

		return true;
	}

	@Override
	public Loader<List<TodoItem>> getLoader(PreparedQuery<TodoItem> query) {
		return new TodoListLoader(this, getHelper().getRuntimeDao(), query);
	}

	@Override
	public QueryBuilder<TodoItem, Integer> getQueryBuilder() {
		return getHelper().getRuntimeDao().queryBuilder();
	}

}
